package com.limh.blehelper.service;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.text.TextUtils;

import com.limh.blehelper.Ble2Manager;
import com.limh.blehelper.event.ConnectEvent;
import com.limh.blehelper.utils.BleLog;

import org.greenrobot.eventbus.EventBus;

public class BlueConnectService extends Service {

    private BluetoothDevice device;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(broadcastReceiver, filter);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        BleLog.d("onStartCommand");
        if (null != intent.getParcelableExtra("device")) {
            device = intent.getParcelableExtra("device");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != broadcastReceiver) {
            unregisterReceiver(broadcastReceiver);
        }
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                switch (action) {
                    case BluetoothDevice.ACTION_ACL_CONNECTED:
                        BleLog.e("BlueConnect=" + device.getAddress());
                        Ble2Manager.getInstance().setCurrentDevice(device);
                        EventBus.getDefault().post(new ConnectEvent(ConnectEvent.CONN_SUCCESS, device));
                        break;
                    case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                        Ble2Manager.getInstance().setCurrentDevice(null);
                        EventBus.getDefault().post(new ConnectEvent(ConnectEvent.CONN_DISCONN, device));
                        stopSelf();
                        break;

                }
            }
        }
    };

}

